package com.ll.app.controller;

import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.ll.app.api.req.SignupApplyReqDTO;
import com.ll.app.api.req.WriteOffReqDTO;
import com.ll.base.dto.ApiResultDTO;
import com.ll.base.enums.QRCodeTypeEnum;
import com.ll.base.util.QRCodeUtils;
import com.ll.domain.user.biz.UserDomainService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;

/**
 * 立木相关的控制器
 *
 * @author WuHen
 * @date 2022/04/29 14:40
 **/
@Slf4j
@RestController
@RequestMapping("/limu")
@RequiredArgsConstructor
@Api(tags = "立木API")
public class LiMuController {

    private final UserDomainService userDomainService;

    @ResponseBody
    @ApiOperation("生成（立木）核销码图片（学员端发起请求）")
    @RequestMapping(value = "/createLMERPic", method = RequestMethod.GET)
    public void createSignupERPic(@RequestParam("userId") Long userId,
                                  HttpServletResponse response) throws IOException {
        // 设置响应流信息
        response.setContentType("image/jpg");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        OutputStream stream = response.getOutputStream();
        //检验积分是否达到
        userDomainService.checkIntegral(Collections.singletonList(userId), 50);


        //type是1，生成活动详情、报名的二维码，type是2，生成活动签到的二维码
        String content = QRCodeTypeEnum.立木核销码.ordinal() + "|" +userId;
        //获取一个二维码图片
        BitMatrix bitMatrix = QRCodeUtils.createCode(content);
        //以流的形式输出到前端
        MatrixToImageWriter.writeToStream(bitMatrix , "jpg" , stream);
    }

    @ResponseBody
    @ApiOperation("核销")
    @RequestMapping(value = "/writeOff", method = RequestMethod.POST)
    public ApiResultDTO writeOff(@RequestBody @Validated WriteOffReqDTO reqDTO){
         userDomainService.writeOff(reqDTO);
         return ApiResultDTO.success();
    }
}
